package services;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import javax.jws.WebMethod;
import javax.jws.WebService;
import middlewareWeb.*;

/**
 *Chasse che modellizza i ReplicaManager
 * @author myusy
 */
@WebService()
public class ReplicaManager implements Observer{
    private static FrontEndQueue bufferRM = new FrontEndQueue();
    private static HashMap<String,TQueueManager> codeMapping = new HashMap<String,TQueueManager>();

    /**
     * Metodo costruttore
     */
    public ReplicaManager()
    {
        bufferRM.addObserver(this);
    }
    /**
     * Servizio ch einserisce nell'attributo bufferRM l'informazione ricevuta
     * @param id id delcomponente
     * @param op numero di sequenza dell'operazione
     * @param idtask id del task
     * @param type tipo del task
     * @param port porta del componente
     * @param ip indirizzo ip
     * @param comm tipo di comando
     * @param link link alla risorsa
     * @return boolean: true se l'operazione è andata a buon fine, false altrimenti
     */
    @WebMethod
    public boolean reply(String id,String op,int idtask,Integer type, int port, String ip, String comm,String link){
        InfoRM info = new InfoRM(id,op,new TaskDescriptor(idtask,TaskTYPE.values()[type],comm,link),new Address(port,ip));
        bufferRM.inserisci(info);
        return true;
    }
    /**
     * Metodo override dell'interfaccia Observer
     * Opera l'operazione di replica
     * @param o
     * @pram arg
     */
    @Override
    public synchronized void update(Observable o, Object arg) {
        if (((FrontEndQueue)o).getCoda().size()>0) {
            InfoRM info = ((FrontEndQueue)o).getCoda().firstElement();
            if (info != null) {
                String componentId = info.getComponentId();
                if(!codeMapping.containsKey(componentId)){
                    codeMapping.put(componentId, new TQueueManager());
                }
                if (info.getOperation().compareTo("enqueue")==0){
                    codeMapping.get(componentId).setAddr(info.getAddress());
                    codeMapping.get(componentId).enqueue(info.getTask());
                    scriviFile(info.getOperation(),codeMapping.get(componentId).toString());
                }else{
                    codeMapping.get(componentId).dequeue();
                    scriviFile(info.getOperation(),codeMapping.get(componentId).toString());
                }
                ((FrontEndQueue)o).getCoda().removeElementAt(0);
            }
        }
    }
    
    private synchronized String scriviFile(String op,String s){
        String path = "/home/myusy/NetBeansProjects/MiddleWareWebApp/TransactionFile/ReplicaManager.txt";
        try {
          File file = new File(path);
          FileWriter fw;
          if(file.exists())
            fw = new FileWriter(file,true);
          else
            fw = new FileWriter(file);
          BufferedWriter bw = new BufferedWriter(fw);
          bw.write(op.toUpperCase()+"\n"+s+"\n");
          bw.flush();
          bw.close();
        }
        catch(IOException e) {
          e.printStackTrace();
        }
        return s;
    }
}
